package com.kexinde.weike.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.configuration.PropertyConfigurator;

public class JdbcUtils {
	private final static Logger logger = Logger.getLogger(JdbcUtils.class);
	static {
		try {
			PropertyConfigurator.configure(JdbcUtils.class.getClassLoader().getResource("").getPath() + "Proxool.properties");
//			JAXPConfigurator.configure("src/java-test/org/logicalcobwebs/proxool/configuration/test-no-ns.xml", false);
			// The false means non-validating 
		} catch (ProxoolException e) {
			logger.error(e.getMessage());
		}
	}

	/**
	 * 连接数据库
	 * 
	 * @return
	 * @throws ConnDBException
	 */
	public static Connection getConnection() throws Exception {

		Connection conn = null;
		try {
			Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
			conn = DriverManager.getConnection("proxool.cmsdata"); // 从连接池取得连接
		} catch (Exception e) {
			logger.error("获取数据库连接失败！ " + e.getMessage(), e);
			throw new Exception("获取数据库连接失败！ " + e.getMessage(), e);
		}
		return conn;

		/*
		 * Connection conn = null; String url = "jdbc:mysql://localhost:3306/upshelf?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "kingkit"; try {
		 * Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new
		 * Exception("数据库连接错误!"); } catch (SQLException e) { e.printStackTrace(); throw new Exception("数据库连接错误!"); } return conn;
		 */
	}

	public static void close(Connection conn) throws Exception {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new Exception("关闭数据库失败!");
			}
		}
	}

	public static void close(Statement stmt) throws Exception {
		if (null != stmt) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new Exception("关闭数据库失败!");
			}
		}
	}

	public static void close(PreparedStatement pstmt) throws Exception {
		if (null != pstmt) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new Exception("关闭数据库失败!");
			}
		}
	}

	public static void close(ResultSet rs) throws Exception {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new Exception("关闭数据库失败!");
			}
		}
	}

}
